package com.grupoconstruobras.sigo.general.util;

import java.sql.Connection;
import java.sql.SQLException;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.Session;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.engine.spi.SessionFactoryImplementor;

public abstract class JpaManager implements IJpaManager {
	protected EntityManager entityManager;
	@PersistenceContext(unitName="default")
	private EntityManager entityManagerDefault;
	/*@PersistenceContext(unitName="fiscalia")
	private EntityManager entityManagerFiscalia;*/
	
	@PostConstruct
	protected void init() {
		entityManager = getEntityManager(EntityManagerType.BIENES);
	}
	
	protected void changeEntityManager(EntityManagerType type) {
		entityManager = getEntityManager(type);
	}

	public Session getSession() {
	  Session session = entityManager.unwrap(Session.class);
	  return session;
	}
	
  public Connection getConnection() throws SQLException {
	  Session session = entityManager.unwrap(Session.class);
	  SessionFactoryImplementor sfi = (SessionFactoryImplementor) session.getSessionFactory();
	  ConnectionProvider cp = sfi.getConnectionProvider();
	  Connection conn = cp.getConnection();
	  return conn;
  }
  
  	private EntityManager getEntityManager(EntityManagerType type) {
		switch(type) {
			/*case FISCALIA:
				return entityManagerFiscalia;*/
			default:
				return entityManagerDefault;
		}
	}
	
}
